package jnpf.message.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrPool;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.Pagination;
import jnpf.base.UserInfo;
import jnpf.base.service.SuperServiceImpl;
import jnpf.config.ConfigValueUtil;
import jnpf.config.JnpfOauthConfig;
import jnpf.database.util.ConnUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.message.entity.*;
import jnpf.message.mapper.MessageMapper;
import jnpf.message.model.NoticePagination;
import jnpf.message.model.SentFlowMessageModel;
import jnpf.message.model.SentMessageForm;
import jnpf.message.model.mq.SentMessageModel;
import jnpf.message.service.*;
import jnpf.message.util.PushMessageUtil;
import jnpf.message.util.SentMessageUtil;
import jnpf.message.util.unipush.UinPush;
import jnpf.util.*;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消息实例
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @date 2019年9月27日 上午9:18
 */
@Service
@Slf4j
@EnableBinding(Processor.class)
public class MessageServiceImpl extends SuperServiceImpl<MessageMapper, MessageEntity> implements MessageService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private MessagereceiveService messagereceiveService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DataSourceUtil dataSourceUtils;
    @Autowired
    private Source source;
    @Autowired
    private SentMessageUtil sentMessageUtil;
    @Autowired
    private MessageTemplateConfigService messageTemplateConfigService;
    @Autowired
    private MessageMonitorService messageMonitorService;
    @Autowired
    private ShortLinkService shortLinkService;
    @Autowired
    private JnpfOauthConfig jnpfOauthConfig;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private UinPush uinPush;
    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private SendMessageConfigService sendMessageConfigService;
    @Autowired
    private SendConfigTemplateService sendConfigTemplateService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DataSource dataSource;
    private final String cacheKey = "message_";

    @Override
    public List<MessageEntity> getNoticeList(NoticePagination pagination) {
        // 定义变量判断是否需要使用修改时间倒序
        QueryWrapper<MessageEntity> queryWrapper = new QueryWrapper<>();
        //关键词（消息标题）
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
            queryWrapper.lambda().like(MessageEntity::getTitle, pagination.getKeyword());
        }
        // 类型
        if (CollectionUtil.isNotEmpty(pagination.getType())) {
            queryWrapper.lambda().in(MessageEntity::getCategory, pagination.getType());
        }
        // 状态
        if (CollectionUtil.isNotEmpty(pagination.getEnabledMark())) {
            queryWrapper.lambda().in(MessageEntity::getEnabledMark, pagination.getEnabledMark());
        } else {
            queryWrapper.lambda().and(t->t.ne(MessageEntity::getEnabledMark, 3).or().isNull(MessageEntity::getEnabledMark));
        }
        // 发布人
        if (CollectionUtil.isNotEmpty(pagination.getReleaseUser())) {
            queryWrapper.lambda().in(MessageEntity::getLastModifyUserId, pagination.getReleaseUser());
        }
        // 发布时间
        if (CollectionUtil.isNotEmpty(pagination.getReleaseTime())) {
            queryWrapper.lambda().between(MessageEntity::getLastModifyTime, new Date(pagination.getReleaseTime().get(0)), new Date(pagination.getReleaseTime().get(1)));
        }
        // 失效时间
        if (CollectionUtil.isNotEmpty(pagination.getExpirationTime())) {
            queryWrapper.lambda().between(MessageEntity::getExpirationTime, new Date(pagination.getExpirationTime().get(0)), new Date(pagination.getExpirationTime().get(1)));
        }
        // 创建人
        if (CollectionUtil.isNotEmpty(pagination.getCreatorUser())) {
            queryWrapper.lambda().in(MessageEntity::getCreatorUserId, pagination.getCreatorUser());
        }
        // 创建时间
        if (CollectionUtil.isNotEmpty(pagination.getCreatorTime())) {
            queryWrapper.lambda().between(MessageEntity::getCreatorTime, new Date(pagination.getCreatorTime().get(0)), new Date(pagination.getCreatorTime().get(1)));
        }
        //默认排序
        queryWrapper.lambda().orderByAsc(MessageEntity::getEnabledMark).orderByDesc(MessageEntity::getLastModifyTime).orderByDesc(MessageEntity::getCreatorTime);
        queryWrapper.lambda().select(MessageEntity::getId, MessageEntity::getCreatorUserId, MessageEntity::getEnabledMark,
                MessageEntity::getLastModifyTime, MessageEntity::getTitle, MessageEntity::getCreatorTime,
                MessageEntity::getLastModifyUserId, MessageEntity::getExpirationTime, MessageEntity::getCategory);
        Page<MessageEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<MessageEntity> userIPage = this.page(page, queryWrapper);
        return pagination.setData(userIPage.getRecords(), page.getTotal());
    }

    @Override
    public List<MessageEntity> getNoticeList() {
        QueryWrapper<MessageEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageEntity::getEnabledMark, 1);
        queryWrapper.lambda().orderByDesc(MessageEntity::getLastModifyTime);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<MessageEntity> getDashboardNoticeList(List<String> typeList) {
        List<MessageEntity> list = new ArrayList<>(16);
        // 判断哪些消息是自己接收的
        QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageReceiveEntity::getUserId, userProvider.get().getUserId());
        queryWrapper.lambda().eq(MessageReceiveEntity::getType, 1);
        List<MessageReceiveEntity> receiveEntities = messagereceiveService.list(queryWrapper);
        for (int i = 0; i < receiveEntities.size(); i++) {
            // 得到message
            MessageReceiveEntity messageReceiveEntity = receiveEntities.get(i);
            MessageEntity entity = JsonUtil.getJsonToBean(messageReceiveEntity.getBodyText(), MessageEntity.class);
            if (entity != null) {
                if (StringUtil.isNotEmpty(entity.getId())) {
                    MessageEntity messageEntity = this.getInfo(entity.getId());
                    if (messageEntity != null) {
                        if ((typeList != null && typeList.size() > 0 && typeList.contains(messageEntity.getCategory()) || typeList == null || typeList.size() == 0)) {
                            if (Objects.equals(messageEntity.getEnabledMark(), 1)
                                    && (entity.getExpirationTime() == null || entity.getExpirationTime().getTime() > System.currentTimeMillis())) {
                                messageEntity.setId(messageReceiveEntity.getId());
                                list.add(messageEntity);
                            }
                        }
                    }
                }
            }
            if (list.size() > 49) {
                break;
            }
        }
        list = list.stream().sorted(Comparator.comparing(MessageEntity::getLastModifyTime).reversed()).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<MessageReceiveEntity> getMessageList1(Pagination pagination, Integer type,Integer isRead) {
        QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageReceiveEntity::getUserId, UserProvider.getLoginUserId());
        if (type != null) {
            queryWrapper.lambda().eq(MessageReceiveEntity::getType, type);
        }
        if (isRead != null) {
            queryWrapper.lambda().eq(MessageReceiveEntity::getIsRead, isRead);
        }
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            queryWrapper.lambda().and(t -> {
                t.like(MessageReceiveEntity::getTitle, pagination.getKeyword());
            });
        }
        queryWrapper.lambda().orderByDesc(MessageReceiveEntity::getCreatorTime);
        Page<MessageReceiveEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<MessageReceiveEntity> userIPage = messagereceiveService.page(page, queryWrapper);
        return pagination.setData(userIPage.getRecords(), page.getTotal());
    }

    public List<MessageReceiveEntity> getMessageList2(Pagination pagination, Integer type, String user,Integer isRead) {
        String userId = StringUtil.isEmpty(user) ? userProvider.get().getUserId() : user;
        Map<String, Object> map = new HashMap<>(16);
        map.put("userId", userId);
        //关键词（消息标题）
        String keyword = pagination.getKeyword();
        if (!StringUtil.isEmpty(keyword)) {
            map.put("keyword", "%" + keyword + "%");
        }
        //消息类别
        if (!ObjectUtils.isEmpty(type)) {
            map.put("type", type);
        }
        //消息是否已读
        if (!ObjectUtils.isEmpty(isRead)) {
            map.put("isRead", isRead);
        }
        List<MessageReceiveEntity> lists = this.baseMapper.getMessageList(map);
        return pagination.setData(PageUtil.getListPage((int) pagination.getCurrentPage(), (int) pagination.getPageSize(), lists), lists.size());
    }

    @Override
    public List<MessageReceiveEntity> getMessageList3(Pagination pagination, Integer type, String user,Integer isRead) {
        QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageReceiveEntity::getUserId, UserProvider.getLoginUserId());
        if (type != null) {
            queryWrapper.lambda().eq(MessageReceiveEntity::getType, type);
        }
        if (isRead != null) {
            queryWrapper.lambda().eq(MessageReceiveEntity::getIsRead, isRead);
        }
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            queryWrapper.lambda().and(t -> {
                t.like(MessageReceiveEntity::getTitle, pagination.getKeyword());
            });
        }
        queryWrapper.lambda().orderByDesc(MessageReceiveEntity::getCreatorTime);
        Page<MessageReceiveEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<MessageReceiveEntity> userIPage = messagereceiveService.page(page, queryWrapper);
        return pagination.setData(userIPage.getRecords(), page.getTotal());
    }


    @Override
    public List<MessageReceiveEntity> getMessageList(Pagination pagination, Integer type, String user) {
        String userId = StringUtil.isEmpty(user) ? userProvider.get().getUserId() : user;
        Map<String, Object> map = new HashMap<>(16);
        map.put("userId", userId);
        //关键词（消息标题）
        String keyword = pagination.getKeyword();
        if (!StringUtil.isEmpty(keyword)) {
            map.put("keyword", "%" + keyword + "%");
        }
        //消息类别
        if (!ObjectUtils.isEmpty(type)) {
            map.put("type", type);
        }
        List<MessageReceiveEntity> lists = this.baseMapper.getMessageList(map);
        return pagination.setData(PageUtil.getListPage((int) pagination.getCurrentPage(), (int) pagination.getPageSize(), lists), lists.size());
    }

    @Override
    public List<MessageReceiveEntity> getMessageList(Pagination pagination) {
        return this.getMessageList(pagination, null, null);
    }

    @Override
    public MessageEntity getInfo(String id) {
        QueryWrapper<MessageEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public MessageEntity getInfoDefault(int type) {
        QueryWrapper<MessageEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageEntity::getEnabledMark, 1);
        if (type == 1) {
            queryWrapper.lambda().orderByDesc(MessageEntity::getCreatorTime);
        } else {
            queryWrapper.lambda().orderByDesc(MessageEntity::getLastModifyTime);
        }
        // 只查询id
        queryWrapper.lambda().select(MessageEntity::getId, MessageEntity::getTitle, MessageEntity::getCreatorTime);
        List<MessageEntity> list = this.page(new Page<>(1, 1), queryWrapper).getRecords();
        MessageEntity entity = new MessageEntity();
        if (list.size() > 0) {
            entity = list.get(0);
        }
        return entity;
    }

    @Override
    @Transactional
    public void delete(MessageEntity entity) {
        this.removeById(entity.getId());
    }

    @Override
    public void create(MessageEntity entity) {
        entity.setId(RandomUtil.uuId());
        entity.setBodyText(XSSEscape.escapeImgOnlyBase64(entity.getBodyText()));
        entity.setEnabledMark(0);
        entity.setCreatorUserId(userProvider.get().getUserId());
        this.save(entity);
    }

    @Override
    public boolean update(String id, MessageEntity entity) {
        entity.setId(id);
        entity.setBodyText(XSSEscape.escapeImgOnlyBase64(entity.getBodyText()));
        entity.setCreatorUserId(userProvider.get().getUserId());
        entity.setLastModifyUserId(null);
        entity.setLastModifyTime(null);
        return this.updateById(entity);
    }

    @Override
    public MessageReceiveEntity messageRead(String messageId) {
        String userId = userProvider.get().getUserId();
        QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageReceiveEntity::getUserId, userId).eq(MessageReceiveEntity::getId, messageId);
        MessageReceiveEntity entity = messagereceiveService.getOne(queryWrapper);
        if (entity != null) {
            entity.setIsRead(1);
            messagereceiveService.updateById(entity);
        }
        return entity;
    }

    @Override
    @DSTransactional
    public void messageRead(List<String> idList) {
        String userId = userProvider.get().getUserId();
        QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MessageReceiveEntity::getUserId, userId).eq(MessageReceiveEntity::getIsRead, 0);
//        queryWrapper.lambda().in(MessageReceiveEntity::getMessageId, idList);
        List<MessageReceiveEntity> entitys = messagereceiveService.list(queryWrapper);
        if (entitys.size() > 0) {
            for (MessageReceiveEntity entity : entitys) {
                entity.setIsRead(1);
                messagereceiveService.updateById(entity);
            }
        }
    }

    @Override
    @Transactional
    public void deleteRecord(List<String> messageIds) {
        // 删除已读表
        QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
        if (messageIds.size() > 0) {
            queryWrapper.lambda().in(MessageReceiveEntity::getId, messageIds);
        }
        // 通过id删除无需判断接收人
        queryWrapper.lambda().eq(MessageReceiveEntity::getUserId, UserProvider.getLoginUserId());
        messagereceiveService.remove(queryWrapper);
    }

    @Override
    public int getUnreadCount(String userId, Integer type) {
        int result = this.baseMapper.getUnreadCount(userId,type);
        return result;
    }

    @Override
    public boolean sentNotice(List<String> toUserIds, MessageEntity entity) {
        // 将所有用户的id存储到redis中
        String key = cacheKey + RandomUtil.uuId();
        redisUtil.insert(key, toUserIds, 3600);
        // 修改状态
        UserInfo userInfo = userProvider.get();
        MessageReceiveEntity messageReceiveEntitys = new MessageReceiveEntity();
        // 推送到mq
        try {
            entity.setEnabledMark(1);
            entity.setLastModifyTime(new Date());
            entity.setLastModifyUserId(userInfo.getUserId());
            this.updateById(entity);
            messageReceiveEntitys.setId(RandomUtil.uuId());
            messageReceiveEntitys.setBodyText(JsonUtil.getObjectToString(entity));
            messagereceiveService.save(messageReceiveEntitys);
            entity.setBodyText(null);
            executeInsert(toUserIds, entity, userInfo, key, messageReceiveEntitys.getId());
            return true;
        } catch (Exception e) {
            entity.setLastModifyTime(null);
            entity.setLastModifyUserId(null);
            entity.setEnabledMark(0);
            this.updateById(entity);
            messagereceiveService.removeById(messageReceiveEntitys.getId());
            log.error("发送公告失败，错误为：" + e.getMessage() + "---\n开始回滚数据，具体信息，消息Id：" + entity.getId() + "，发送人：" + userInfo.getUserId());
            return false;
        }
//        //消息推送 - APP
//        GetuiAppPushUtil getuiAppPushUtil = new GetuiAppPushUtil(configValueUtil.getIgexinAppid(), configValueUtil.getIgexinAppkey(), configValueUtil.getIgexinMastersecret(), Boolean.parseBoolean(configValueUtil.getIgexinEnabled()));
//        getuiAppPushUtil.SendNotice(userInfo.getTenantId(), toUserIds, "系统公告", entity.getTitle(), "1");
    }

    /**
     * 分段推送到mq中
     *
     * @param toUserIds 接受者id
     * @param entity
     * @param userInfo
     * @throws Exception
     */
    private void executeInsert(List<String> toUserIds, MessageEntity entity, UserInfo userInfo, String key, String receiveId) throws Exception {
        try {
            int frequency = 10000;
            int count = toUserIds.size() / frequency + 1;
            if (toUserIds.size() < 1) return;
            boolean countEnd = false;
            for (int i = 0; i < count; i++) {
                // 存到redis
                int endSize = Math.min(((i + 1) * frequency), toUserIds.size());
                // 开始推送
                if (i == count - 1) {
                    countEnd = true;
                }
                SentMessageModel sentMessageModel = new SentMessageModel(toUserIds.subList(i * frequency, endSize), entity, userInfo, countEnd, key, receiveId);
                source.output().send(
                        MessageBuilder.withPayload(
                                JsonUtil.getObjectToString(sentMessageModel)
                        )
                                .setHeader("type", "sentNotice")
                                .build()
                );
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }

    @StreamListener(value = Processor.INPUT, condition = "headers['type']=='sentNotice'")
    public void receive(String messageBody) {
        SentMessageModel model = JsonUtil.getJsonToBean(messageBody, SentMessageModel.class);
        try {
            UserInfo userInfo = model.getUserInfo();
            UserProvider.setLocalLoginUser(userInfo);
            if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
                TenantDataSourceUtil.switchTenant(userInfo.getTenantId());
            }
//            // 直接写入消息监控中
//            executeBatchMonitor(model.getIdList(), model.getEntity(), model.getUserInfo());
            // 发送公告
            executeBatch(model.getIdList(), model.getEntity(), model.getUserInfo(), model.getCountEnd(), model.getCacheKey(), model.getReceiveId());
        } catch (Exception e) {
            QueryWrapper<MessageReceiveEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
//                    .eq(MessageReceiveEntity::getMessageId, model.getEntity().getId())
                    .eq(MessageReceiveEntity::getUserId, model.getUserInfo().getUserId());
            messagereceiveService.remove(queryWrapper);
        } finally {
            TenantDataSourceUtil.clearLocalTenantInfo();
            UserProvider.clearLocalUser();
        }
    }


    /**
     * 执行发送操作
     *
     * @param idList   存到redis中的key
     * @param entity
     * @param userInfo
     */
    private void executeBatch(List<String> idList, MessageEntity entity, UserInfo userInfo, Boolean countEnd, String cacheKey, String receiveId) {
        if (idList.size() == 0 || "3".equals(String.valueOf(entity.getRemindCategory()))) {
            return;
        }
        SentMessageForm sentMessageForm = new SentMessageForm();
        sentMessageForm.setToUserIds(idList);
        sentMessageForm.setTitle(entity.getTitle());
        sentMessageForm.setContent(entity.getBodyText());
        sentMessageForm.setContentMsg(Collections.EMPTY_MAP);
        sentMessageForm.setUserInfo(userInfo);
        sentMessageForm.setType(1);
        sentMessageForm.setId(entity.getId());
        sentMessageForm.setReceiveId(receiveId);

        // 站内信
        if ("1".equals(String.valueOf(entity.getRemindCategory()))) {
            message(sentMessageForm);
        } else if ("2".equals(String.valueOf(entity.getRemindCategory()))) {
            SendMessageConfigEntity sendMessageConfigEntity = sendMessageConfigService.getInfo(entity.getSendConfigId());
            if (sendMessageConfigEntity != null) {
                List<SendConfigTemplateEntity> configTemplateEntityList = sendConfigTemplateService.getDetailListByParentId(sendMessageConfigEntity.getId());
                for (SendConfigTemplateEntity sendConfigTemplateEntity : configTemplateEntityList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("Title", entity.getTitle());
                    map.put("Content", entity.getBodyText());
                    map.put("Remark", entity.getExcerpt());
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("@title", entity.getTitle());
                    paramMap.put("@Content", entity.getBodyText());
                    paramMap.put("@Remark", entity.getExcerpt());
                    switch (sendConfigTemplateEntity.getMessageType()) {
                        case "1" :
                            MessageTemplateConfigEntity configEntity = messageTemplateConfigService.getInfo(sendConfigTemplateEntity.getTemplateId());
                            if (configEntity != null) {
                                sentMessageForm.setTitle(configEntity.getTitle());
                            }
                            message(sentMessageForm);
                            break;
                        case "2":
                            // 邮件
                            sentMessageUtil.SendMail(idList, userInfo, "2", sendConfigTemplateEntity, new HashMap<>(), map);
                            break;
                        case "3":
                            // 发送短信
                            sentMessageUtil.sendSms(idList, userInfo, sendConfigTemplateEntity, paramMap, new HashMap<>());
                            break;
                        case "4":
                            // 钉钉
                            JSONObject jsonObject1 = sentMessageUtil.SendDingTalk(idList, userInfo, "4", sendConfigTemplateEntity, new HashMap<>(), map);
                            if (!(Boolean) jsonObject1.get("code")) {
                                log.error("发送企业微信消息失败，错误：" + jsonObject1.get("error"));
                            }
                            break;
                        case "5":
                            // 企业微信
                            JSONObject jsonObject = sentMessageUtil.SendQyWebChat(idList, userInfo, "5", sendConfigTemplateEntity, new HashMap<>(), map);
                            if (!(Boolean) jsonObject.get("code")) {
                                log.error("发送企业微信消息失败，错误：" + jsonObject.get("error"));
                            }
                            break;
                        case "6":
                            // webhook
                            sentMessageUtil.SendWebHook(null, userInfo, sendConfigTemplateEntity, new HashMap<>(), map);
                            break;
                        case "7":
                            // 微信公众号
                            sentMessageUtil.SendWXGzhChat(idList, userInfo, "7", sendConfigTemplateEntity, new HashMap<>(), paramMap);
                            break;
                        default:
                            break;
                    }
                }

            }
        }
        /*
        try {
            String column_key = StringUtil.EMPTY, column_plceholder = StringUtil.EMPTY, column_value = TenantDataSourceUtil.getTenantColumn();
            if (StringUtil.isNotEmpty(column_value)) {
                column_key = StrPool.COMMA + configValueUtil.getMultiTenantColumn();
                column_plceholder = ",?";
            }
            @Cleanup Connection conn = ConnUtil.getConnOrDefault(null);
            @Cleanup PreparedStatement pstm = null;
            String sql = "INSERT INTO base_messagereceive(F_ID,F_MESSAGEID,F_USERID,F_ISREAD,F_BODYTEXT" + column_key + ")  VALUES (?,?,?,?,?" + column_plceholder + ")";

            pstm = conn.prepareStatement(sql);
            conn.setAutoCommit(false);
            for (String toUserId : idList) {
                pstm.setString(1, RandomUtil.uuId());
                pstm.setString(2, entity.getId());
                pstm.setString(3, toUserId);
                pstm.setInt(4, 0);
                pstm.setString(5, entity.getBodyText());
                if(StringUtil.isNotEmpty(column_value)){
                    pstm.setString(6, column_value);
                }
                pstm.addBatch();
            }
            long time = System.currentTimeMillis();
            log.info("开始提交事务，时间：" + time);
            pstm.executeBatch();
            conn.commit();
            long endTime = System.currentTimeMillis();
            log.info("事务提交完成：" + endTime + "耗时：" + (endTime - time));
            pstm.close();
            conn.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("发送消息发生错误，发送人：" + userInfo.getUserId());
        }
        if (countEnd) {
            //消息推送 - PC端
            List<List<String>> list = (List) redisUtil.get(cacheKey, 0, -1);
            PushMessageUtil.pushMessage(list.get(0), entity, userInfo, 1);
        }
        */
    }

    /**
     * 写入消息监控中
     *
     * @param idList
     * @param entity
     * @param userInfo
     */
    private void executeBatchMonitor(List<String> idList, MessageEntity entity, UserInfo userInfo) {
        try {
            if ("3".equals(String.valueOf(entity.getRemindCategory()))) {
                return;
            }
            String column_key = StringUtil.EMPTY, column_plceholder = StringUtil.EMPTY, column_value = TenantDataSourceUtil.getTenantColumn();
            if (StringUtil.isNotEmpty(column_value)) {
                column_key = StrPool.COMMA + configValueUtil.getMultiTenantColumn();
                column_plceholder = ",?";
            }
            @Cleanup Connection conn = ConnUtil.getConnOrDefault(null);
            @Cleanup PreparedStatement pstm = null;
            String sql = "INSERT INTO base_message_monitor(F_Id,F_AccountId,F_AccountName,F_AccountCode,F_MessageType,F_MessageSource," +
                    "F_SendTime,F_MessageTemplateId,F_Title,F_ReceiveUser,F_Content,F_CreatorTime,F_CreatorUserId,F_LastModifyTime,F_LastModifyUserId," +
                    "F_DeleteMark,F_DeleteTime,F_DeleteUserId,F_TenantId,F_EnabledMark" +
                    column_key + ")  VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?" + column_plceholder + ")";

            pstm = conn.prepareStatement(sql);
            conn.setAutoCommit(false);

            // 站内信
            if ("1".equals(String.valueOf(entity.getRemindCategory()))) {
                // 获取发送配置详情
                SendMessageConfigEntity sendMessageConfigEntity = sendMessageConfigService.getSysConfig("MBXTGG001", "1");
                // 消息发送模板
                MessageTemplateConfigEntity messageTemplateConfigEntity = messageTemplateConfigService.getInfoByEnCode("MBXTGG001", "1");
                batchRecord(idList, sendMessageConfigEntity, messageTemplateConfigEntity, entity, userInfo, pstm);
            } else if ("2".equals(String.valueOf(entity.getRemindCategory()))) {
                SendMessageConfigEntity sendMessageConfigEntity = sendMessageConfigService.getInfo(entity.getSendConfigId());
                if (sendMessageConfigEntity != null) {
                    List<SendConfigTemplateEntity> configTemplateEntityList = sendConfigTemplateService.getDetailListByParentId(sendMessageConfigEntity.getId());
                    for (SendConfigTemplateEntity sendConfigTemplateEntity : configTemplateEntityList) {
                        // 模板id不等于空的
                        if (StringUtil.isNotEmpty(sendConfigTemplateEntity.getTemplateId())) {
                            MessageTemplateConfigEntity messageTemplateConfigEntity = messageTemplateConfigService.getInfo(sendConfigTemplateEntity.getTemplateId());
                            if (messageTemplateConfigEntity != null) {
                                // 如果是webhook
                                if ("2".equals(messageTemplateConfigEntity.getMessageSource()) && "6".equals(messageTemplateConfigEntity.getMessageType())) {
                                    pstm.setString(1, RandomUtil.uuId());
                                    pstm.setString(2, sendMessageConfigEntity.getId());
                                    pstm.setString(3, sendMessageConfigEntity.getFullName());
                                    pstm.setString(4, sendMessageConfigEntity.getEnCode());
                                    pstm.setString(5, "6");
                                    pstm.setString(6, "1");
                                    pstm.setDate(7, new java.sql.Date(System.currentTimeMillis()));
                                    pstm.setString(8, messageTemplateConfigEntity.getId());
                                    pstm.setString(9, entity.getTitle());
                                    pstm.setString(10, JsonUtil.getObjectToString(entity.getToUserIds()));
                                    pstm.setString(11, entity.getBodyText());
                                    pstm.setDate(12, new java.sql.Date(System.currentTimeMillis()));
                                    pstm.setString(13, userInfo.getUserId());
                                    pstm.addBatch();
                                } else {
                                    batchRecord(idList, sendMessageConfigEntity, messageTemplateConfigEntity, entity, userInfo, pstm);
                                }
                            }
                        }
                    }
                }
            }
            long time = System.currentTimeMillis();
            log.info("开始提交事务，时间：" + time);
            pstm.executeBatch();
            conn.commit();
            long endTime = System.currentTimeMillis();
            log.info("事务提交完成：" + endTime + "耗时：" + (endTime - time));
            pstm.close();
            conn.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("发送消息发生错误，发送人：" + userInfo.getUserId());
        }

    }

    /**
     * 批量加入消息记录
     *
     * @param idList                        接收人
     * @param sendMessageConfigEntity       发送配置
     * @param messageTemplateConfigEntity   发送模板配置
     * @param entity                        消息实体
     * @param userInfo                      用户信息
     * @param pstm                          PreparedStatement对象
     * @throws SQLException
     */
    private void batchRecord(List<String> idList, SendMessageConfigEntity sendMessageConfigEntity, MessageTemplateConfigEntity messageTemplateConfigEntity,
                             MessageEntity entity, UserInfo userInfo, PreparedStatement pstm) throws SQLException {
        for (String toUserId : idList) {
            // 插入参数
            pstm.setString(1, RandomUtil.uuId());
            if (sendMessageConfigEntity != null) {
                pstm.setString(2, sendMessageConfigEntity.getId());
                pstm.setString(3, sendMessageConfigEntity.getFullName());
                pstm.setString(4, sendMessageConfigEntity.getEnCode());
                pstm.setString(5, messageTemplateConfigEntity.getMessageSource());
                pstm.setString(6, messageTemplateConfigEntity.getMessageType());
                pstm.setDate(7, new java.sql.Date(System.currentTimeMillis()));
                pstm.setString(8, messageTemplateConfigEntity.getId());
                pstm.setString(9, entity.getTitle());
                pstm.setString(10, toUserId);
                pstm.setString(11, entity.getBodyText());
                pstm.setDate(12, new java.sql.Date(System.currentTimeMillis()));
                pstm.setString(13, userInfo.getUserId());
                pstm.addBatch();
            }
        }
    }

    /**
     * Mq监听器
     *
     * @param flowMessageModel 发送消息模型
     */
    @StreamListener(value = Processor.INPUT, condition = "headers['type']=='sentMessage'")
    public void sentMessage(String flowMessageModel) {
        try {
            SentFlowMessageModel sentFlowMessageModel = JsonUtil.getJsonToBean(flowMessageModel, SentFlowMessageModel.class);
            UserInfo userInfo = sentFlowMessageModel.getUserInfo();
            UserProvider.setLocalLoginUser(userInfo);
            if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
                TenantDataSourceUtil.switchTenant(userInfo.getTenantId());
            }
            List<String> toUserIdsList = sentFlowMessageModel.getToUserIdsList();
            // 消费消息
            String sendType = sentFlowMessageModel.getSendType();
            switch (sendType) {
                case "1":
                    // 站内消息
                    for (String toUserId : toUserIdsList) {
                        List<String> toUser = new ArrayList<>();
                        Map<String, String> contentMsg = sentFlowMessageModel.getContentMsg();
                        MessageTemplateConfigEntity templateConfigEntity = messageTemplateConfigService.getInfo(sentFlowMessageModel.getEntity().getTemplateId());
                        String title = sentFlowMessageModel.getTitle();
                        if(templateConfigEntity != null) {
                            title = templateConfigEntity.getTitle();
                            String msg = contentMsg.get(toUserId) != null ? contentMsg.get(toUserId) : "{}";
                            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
                            String encode = Base64.getEncoder().encodeToString(bytes);
                            //流程审批页面链接地址
                            String pcLink = jnpfOauthConfig.getJnpfFrontDomain() + "/workFlowDetail?config=" + encode;
                            String appLink = jnpfOauthConfig.getJnpfAppDomain() + "/pages/workFlow/flowBefore/index?config=" + encode;
                            //转换为短链
                            String shortLink = shortLinkService.shortLink(pcLink + toUserId + templateConfigEntity.getMessageType());
                            shortLink = sentMessageUtil.getShortLink(pcLink, toUserId, shortLink, templateConfigEntity.getMessageType());
                            String link = jnpfOauthConfig.getJnpfDomain() + "/api/message/ShortLink/" + shortLink;
                            if (StringUtil.isNotBlank(userInfo.getTenantId())) {
                                link = link + "/" + userInfo.getTenantId();
                            }
                            if (title.contains("{@FlowLink}")) {
                                title = title.replace("{@FlowLink}", link + " ");
                                //链接数据保存
                                sentMessageUtil.saveShortLink(pcLink, appLink, shortLink, userInfo, toUserId, msg);
                            }
                            Map<String, Object> msgMap = new HashMap<>();
                            msgMap = sentMessageUtil.getParamMap(sentFlowMessageModel.getEntity().getId(), sentFlowMessageModel.getParameterMap());
                            if (StringUtil.isNotEmpty(title)) {
                                StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                                title = strSubstitutor.replace(title);
                            }
                        }
                        toUser.add(toUserId);
                        this.sentMessage(toUser, title, sentFlowMessageModel.getContent(), contentMsg, sentFlowMessageModel.getUserInfo());
                        //消息监控写入
                        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
                        monitorEntity.setId(RandomUtil.uuId());
                        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUser));
                        monitorEntity.setSendTime(DateUtil.getNowDate());
                        monitorEntity.setCreatorTime(DateUtil.getNowDate());
                        monitorEntity.setCreatorUserId(userInfo.getUserId());
                        sentMessageUtil.createMessageMonitor(monitorEntity, templateConfigEntity, null, null, userInfo, sentFlowMessageModel.getToUserIdsList(), title);
                        messageMonitorService.create(monitorEntity);
                    }
                    break;
                case "2":
                    // 邮件
                    sentMessageUtil.SendMail(sentFlowMessageModel.getToUserIdsList(), sentFlowMessageModel.getUserInfo(), sendType, sentFlowMessageModel.getEntity(), sentFlowMessageModel.getParameterMap(), sentFlowMessageModel.getContentMsg());
                    break;
                case "3":
                    // 发送短信
                    sentMessageUtil.sendSms(sentFlowMessageModel.getToUserIdsList(), sentFlowMessageModel.getUserInfo(), sentFlowMessageModel.getEntity(), sentFlowMessageModel.getParameterMap(), sentFlowMessageModel.getContentMsg());
                    break;
                case "4":
                    // 钉钉
                    JSONObject jsonObject1 = sentMessageUtil.SendDingTalk(sentFlowMessageModel.getToUserIdsList(), sentFlowMessageModel.getUserInfo(), sendType, sentFlowMessageModel.getEntity(), sentFlowMessageModel.getParameterMap(), sentFlowMessageModel.getContentMsg());
                    if (!(Boolean) jsonObject1.get("code")) {
                        log.error("发送企业微信消息失败，错误：" + jsonObject1.get("error"));
                    }
                    break;
                case "5":
                    // 企业微信
                    JSONObject jsonObject = sentMessageUtil.SendQyWebChat(sentFlowMessageModel.getToUserIdsList(), sentFlowMessageModel.getUserInfo(), sendType, sentFlowMessageModel.getEntity(), sentFlowMessageModel.getParameterMap(), sentFlowMessageModel.getContentMsg());
                    if (!(Boolean) jsonObject.get("code")) {
                        log.error("发送企业微信消息失败，错误：" + jsonObject.get("error"));
                    }
                    break;
                case "6":
                    // webhook
                    sentMessageUtil.SendWebHook(sendType, userInfo, sentFlowMessageModel.getEntity(), sentFlowMessageModel.getParameterMap(), new HashMap<>());
                    break;
                case "7":
                    // 微信公众号
                    sentMessageUtil.SendWXGzhChat(toUserIdsList, userInfo, sendType, sentFlowMessageModel.getEntity(), sentFlowMessageModel.getContentMsg(), sentFlowMessageModel.getParameterMap());
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            TenantDataSourceUtil.clearLocalTenantInfo();
            UserProvider.clearLocalUser();
        }
    }

    @Override
    @Transactional
    public void sentMessage(List<String> toUserIds, String title, String bodyText) {
        UserInfo userInfo = userProvider.get();

        MessageReceiveEntity messageReceiveEntity = new MessageReceiveEntity();
        messageReceiveEntity.setTitle(title);
        messageReceiveEntity.setType(2);
        messageReceiveEntity.setFlowType(1);
        messageReceiveEntity.setIsRead(0);
        Map<String,MessageReceiveEntity> map = new HashMap<>();
        for (String item : toUserIds) {
            MessageReceiveEntity messageReceiveEntitys = new MessageReceiveEntity();
            BeanUtils.copyProperties(messageReceiveEntity, messageReceiveEntitys);
            messageReceiveEntitys.setId(RandomUtil.uuId());
            messageReceiveEntitys.setUserId(item);
            messageReceiveEntitys.setBodyText(bodyText);
            messagereceiveService.save(messageReceiveEntitys);
            map.put(messageReceiveEntitys.getUserId(), messageReceiveEntitys);
        }
        //直接推送给前端
        PushMessageUtil.pushMessage(map, userInfo, 2);
//        //消息推送 - APP
//        GetuiAppPushUtil getuiAppPushUtil = new GetuiAppPushUtil(configValueUtil.getIgexinAppid(), configValueUtil.getIgexinAppkey(), configValueUtil.getIgexinMastersecret(), Boolean.parseBoolean(configValueUtil.getIgexinEnabled()));
//        getuiAppPushUtil.SendNotice(userInfo.getTenantId(), toUserIds, "系统消息", entity.getTitle(), "2");
    }

    @Override
    @DSTransactional
    public void sentMessage(List<String> toUserIds, String title, String bodyText, Map<String, String> contentMsg, UserInfo userInfo) {
        MessageReceiveEntity messageReceiveEntity = new MessageReceiveEntity();
        messageReceiveEntity.setTitle(title);
        messageReceiveEntity.setType(2);
        messageReceiveEntity.setFlowType(1);
        messageReceiveEntity.setIsRead(0);
        Map<String,MessageReceiveEntity> map = new HashMap<>();
        for (String item : toUserIds) {
            MessageReceiveEntity messageReceiveEntitys = new MessageReceiveEntity();
            BeanUtils.copyProperties(messageReceiveEntity, messageReceiveEntitys);
            messageReceiveEntitys.setId(RandomUtil.uuId());
            messageReceiveEntitys.setUserId(item);
            String msg = contentMsg.get(item) != null ? contentMsg.get(item) : "{}";
            messageReceiveEntitys.setBodyText(msg);
            messageReceiveEntitys.setCreatorTime(new Date());
            messageReceiveEntitys.setCreatorUserId(userInfo.getUserId());
            messagereceiveService.save(messageReceiveEntitys);
            map.put(messageReceiveEntitys.getUserId(), messageReceiveEntitys);
        }
        //消息推送 - PC端
        PushMessageUtil.pushMessage(map, userInfo, 2);
    }

    @Override
    public void sentMessage(List<String> toUserIds, String title, String bodyText, UserInfo userInfo, Integer source, Integer type, boolean testMessage) {
        MessageReceiveEntity messageReceiveEntity = new MessageReceiveEntity();
        messageReceiveEntity.setTitle(title);
        messageReceiveEntity.setType(source);
        messageReceiveEntity.setFlowType(1);
        messageReceiveEntity.setIsRead(0);
        Map<String,MessageReceiveEntity> map = new HashMap<>();
        for (String item : toUserIds) {
            MessageReceiveEntity messageReceiveEntitys = new MessageReceiveEntity();
            BeanUtils.copyProperties(messageReceiveEntity, messageReceiveEntitys);
            messageReceiveEntitys.setId(RandomUtil.uuId());
            messageReceiveEntitys.setUserId(item);
            messagereceiveService.save(messageReceiveEntitys);
            map.put(messageReceiveEntitys.getUserId(), messageReceiveEntitys);
        }
        //消息监控写入
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setTitle(title);
        monitorEntity.setMessageType(String.valueOf(type));
        monitorEntity.setMessageSource(String.valueOf(source));
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIds));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        messageMonitorService.create(monitorEntity);
        //消息推送 - PC端
        PushMessageUtil.pushMessage(map, userInfo, source);
    }

    @Override
    public void sentScheduleMessage(SentMessageForm sentMessageForm, String type) {
        UserInfo userInfo = sentMessageForm.getUserInfo();
        String templateId = sentMessageForm.getTemplateId();
        String title = sentMessageForm.getTitle();
        List<String> toUserIds = sentMessageForm.getToUserIds();
        //获取发送配置详情
        SendMessageConfigEntity configEntity = sendMessageConfigService.getInfoByEnCode(templateId);
        if (configEntity != null) {
            templateId = configEntity.getId();
        } else {
            configEntity = sendMessageConfigService.getInfo(templateId);
        }
        List<SendConfigTemplateEntity> list = sendConfigTemplateService.getDetailListByParentId(templateId);
        if (configEntity != null) {
            for (SendConfigTemplateEntity sendConfigTemplateEntity : list) {
                Map<String, Object> objectMap = new HashMap<>(sentMessageForm.getParameterMap());
                Map<String,Object> parameterMap = new HashMap<>();
                for(String key:objectMap.keySet()){
                    if(key.contains(sendConfigTemplateEntity.getId())){
                        parameterMap.put(key.substring(sendConfigTemplateEntity.getId().length()),objectMap.get(key));
                    }
                }
                parameterMap.putAll(objectMap);
                Map<String, String> contentMsg = new HashMap<>();
                for(String key : parameterMap.keySet()){
                    contentMsg.put(key,String.valueOf(parameterMap.get(key)));
                }
                String sendType = sendConfigTemplateEntity.getMessageType();
                switch (sendType) {
                    case "1":
                        MessageTemplateConfigEntity templateConfigEntity = messageTemplateConfigService.getInfo(sendConfigTemplateEntity.getTemplateId());
                        String messageTitle = StringUtil.isNotEmpty(templateConfigEntity.getTitle()) ? templateConfigEntity.getTitle() : "";
                        String content = StringUtil.isNotEmpty(templateConfigEntity.getContent()) ? templateConfigEntity.getContent() : "";
                        StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                        messageTitle = strSubstitutor.replace(messageTitle);
                        content = strSubstitutor.replace(content);
                        sentMessageForm.setTitle(messageTitle);
                        sentMessageForm.setContent(content);
                        // 站内消息
                        message(sentMessageForm);
                        break;
                    case "2":
                        // 邮件
                        sentMessageUtil.SendMail(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        break;
                    case "3":
                        // 发送短信
                        sentMessageUtil.sendSms(toUserIds, userInfo, sendConfigTemplateEntity, parameterMap, new HashMap<>());
                        break;
                    case "4":
                        // 钉钉
                        JSONObject jsonObject1 = sentMessageUtil.SendDingTalk(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        if (!(Boolean) jsonObject1.get("code")) {
                            log.error("发送企业微信消息失败，错误：" + jsonObject1.get("error"));
                        }
                        break;
                    case "5":
                        // 企业微信
                        JSONObject jsonObject = sentMessageUtil.SendQyWebChat(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(), contentMsg);
                        if (!(Boolean) jsonObject.get("code")) {
                            log.error("发送企业微信消息失败，错误：" + jsonObject.get("error"));
                        }
                        break;
                    case "6":
                        // webhook
                        sentMessageUtil.SendWebHook(sendType, userInfo, sendConfigTemplateEntity, new HashMap<>(),contentMsg);
                        break;
                    case "7":
                        // 微信公众号
                        sentMessageUtil.SendWXGzhChat(toUserIds, userInfo, sendType, sendConfigTemplateEntity, new HashMap<>(),parameterMap);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void message(SentMessageForm sentMessageForm) {
        String receiveId = sentMessageForm.getReceiveId();
        List<String> toUserIds = sentMessageForm.getToUserIds();
        Integer type = sentMessageForm.getType();
        String title = sentMessageForm.getTitle();
        String content = sentMessageForm.getContent();
        String bodyText = Objects.equals(type,3) ? content: JsonUtil.getObjectToString(sentMessageForm.getContentMsg());
        UserInfo userInfo = sentMessageForm.getUserInfo();
        MessageReceiveEntity messageReceiveEntity = new MessageReceiveEntity();
        messageReceiveEntity.setIsRead(0);
        messageReceiveEntity.setId(RandomUtil.uuId());
        messageReceiveEntity.setType(sentMessageForm.getType());
        if (type != null) {
            messageReceiveEntity.setId(sentMessageForm.getId());
            messageReceiveEntity.setType(type);
            messageReceiveEntity.setCreatorUserId(userInfo.getUserId());
            messageReceiveEntity.setCreatorTime(DateUtil.getNowDate());
        }
        //消息监控写入
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        MessageEntity messageEntity = this.getInfo(sentMessageForm.getId());
        if (!"1".equals(String.valueOf(messageReceiveEntity.getType()))) {
            monitorEntity.setMessageSource(sentMessageForm.getType()+"");
            messageReceiveEntity.setFlowType(sentMessageForm.getFlowType());
            monitorEntity.setTitle(title);
        } else {
            monitorEntity.setMessageSource("1");
            title = title.replaceAll("\\{@Title}", messageEntity.getTitle())
                    .replaceAll("\\{@CreatorUserName}", userInfo.getUserName())
                    .replaceAll("\\{@Content}", messageEntity.getBodyText())
                    .replaceAll("\\{@Remark}", StringUtil.isNotEmpty(messageEntity.getExcerpt()) ? messageEntity.getExcerpt() : "");
            monitorEntity.setTitle(title);
            bodyText = JsonUtil.getObjectToString(messageEntity);
        }
        Map<String,MessageReceiveEntity> map = new HashMap<>();
        for (String item : toUserIds) {
            MessageReceiveEntity messageReceiveEntitys = messagereceiveService.getById(receiveId);
            if (messageReceiveEntitys == null) {
                messageReceiveEntitys = new MessageReceiveEntity();
            } else {
                bodyText = messageReceiveEntitys.getBodyText();
            }
            BeanUtils.copyProperties(messageReceiveEntity, messageReceiveEntitys);
            messageReceiveEntitys.setBodyText(bodyText);
            messageReceiveEntitys.setId(RandomUtil.uuId());
            messageReceiveEntitys.setUserId(item);
            messageReceiveEntitys.setTitle(title);
//            if(ObjectUtil.isNotEmpty(messageEntity)) {
//                messageReceiveEntitys.setTitle(title.replaceAll("\\{@Title}", messageEntity.getTitle())
//                        .replaceAll("\\{@CreatorUserName}", userInfo.getUserName())
//                        .replaceAll("\\{@Content}", messageEntity.getBodyText())
//                        .replaceAll("\\{@Remark}", StringUtil.isNotEmpty(messageEntity.getExcerpt()) ? messageEntity.getExcerpt() : ""));
//            }
            messageReceiveEntitys.setCreatorUserId(userInfo.getUserId());
            messageReceiveEntitys.setCreatorTime(new Date());
            messagereceiveService.save(messageReceiveEntitys);
            map.put(messageReceiveEntitys.getUserId(), messageReceiveEntitys);
        }
        messagereceiveService.removeById(receiveId);
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setMessageType("1");
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIds));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        monitorEntity.setContent(content);
        messageMonitorService.create(monitorEntity);
        //消息推送 - PC端
        PushMessageUtil.pushMessage(map, userInfo, 4);
    }

    @Override
    public Boolean updateEnabledMark() {
        QueryWrapper<MessageEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().and(t->t.eq(MessageEntity::getEnabledMark, 1).lt(MessageEntity::getExpirationTime, new Date()));
        List<MessageEntity> list = this.list(queryWrapper);
        List<String> collect = list.stream().map(MessageEntity::getId).collect(Collectors.toList());
        if (collect.size() == 0) {
            return true;
        }
        UpdateWrapper<MessageEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(MessageEntity::getEnabledMark, 2);
        updateWrapper.lambda().in(MessageEntity::getId, collect);
        return this.update(updateWrapper);
    }

}
